//
//  ForgetCipherController.swift
//  YiYaoHui
//
//  Created by HM on 15/12/5.
//  Copyright © 2015年 TMPercy. All rights reserved.
//

import UIKit
import Alamofire

class ForgetCipherController: UIViewController {

    @IBOutlet weak var phoneNumTF: UITextField!
    
    @IBOutlet weak var verifyTF: UITextField!
    
    @IBOutlet weak var getVerifyCodeButton: CountDownButton!
    
    @IBOutlet weak var nextButton: UIButton!
    
    @IBOutlet weak var contentView: UIView!
    
    @IBOutlet weak var getCodeButton: UIButton!
    
    let baseURL = "http://112.74.131.194:8080/MedicineProject/App/getVerificationCode"
    let verifyCodeURL = "http://112.74.131.194:8080/MedicineProject/App/verifyCode"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        phoneNumTF.delegate = self
        verifyTF.delegate = self
        // Do any additional setup after loading the view.
        
        setUpUI()
    }
    
    func setUpUI() {
        
        disableButton()
        
        contentView.layer.borderWidth = 1.0
        contentView.layer.borderColor = UIColor(red: 235/255, green: 235/255, blue: 235/255, alpha: 1).CGColor
        
        nextButton.layer.cornerRadius = 5
        getCodeButton.layer.cornerRadius = 3
    }
    
    //可以按了就可以调整
    func enableButton() {
        nextButton.enabled = true
        
        nextButton.backgroundColor = UIColor(red: 96/255, green: 200/255, blue: 75/255, alpha: 1)
        nextButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
    }
    
    func disableButton() {
        nextButton.enabled = false
        nextButton.backgroundColor = UIColor(red: 150/255, green: 150/255, blue: 150/255, alpha: 1.0)
        nextButton.setTitleColor(UIColor.lightTextColor(), forState: UIControlState.Disabled)
    }
    
    
    override func viewWillAppear(animated: Bool) {
        navigationController?.navigationBarHidden = false
        self.navigationController?.navigationBar.backItem?.title = ""
        self.title = "忘记密码"
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func getVerifyCode(sender: AnyObject) {
        
        dismissKeyboard()
        
        print("有执行获取验证码的方法")
        
        //手机号不能为空
        if (phoneNumTF.text != nil && phoneNumTF.text != "" )
        {
            print("手机号不为空")
            getVerifyCodeButton.originCountDownTime = 60
            getVerifyCodeButton.startCountDown()
            Alamofire.request(.POST, baseURL, parameters: ["phoneNumber":phoneNumTF.text!,"type":"2"], encoding: .URL, headers: nil).responseJSON { (_, _, result) -> Void in
                
                //先判断返回的值是否为空，不为空就执行这一步
                if let  value = result.value {
                    //再判断返回的值是success还是fail
                    let state = value["result"] as! String
                    if state == "success" {
                        print("获取验证码成功的结果",result.value)
                    }
                        //如果返回fail继续检查帐号、密码是否有误。
                    else {
                        print("返回fail")
                        self.alertView()
                    }
                }
                    //为空就检查帐号和密码是否又误
                else {
                    print("返回nil")
                    self.alertView()
                }
            }
        } else {
            print("手机号为空")
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "loginState")
            NSUserDefaults.standardUserDefaults().synchronize()
            let alert = UIAlertController(title: "提示", message: "手机号不能为空", preferredStyle: UIAlertControllerStyle.Alert)
            let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
            alert.addAction(action)
            self.presentViewController(alert, animated: true, completion: nil)
        }
        print("方法执行到最后了")
    }
    
    func alertView() {
        let alert = UIAlertController(title: "您输入的信息有误", message: "请重新输入", preferredStyle: UIAlertControllerStyle.Alert)
        let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
        alert.addAction(action)
        self.presentViewController(alert, animated: true, completion: nil)
    }
    
    //跳之前需要验证 验证码
    @IBAction func next(sender: AnyObject) {
        
        //编辑完了按空白处收键盘
        dismissKeyboard()
        
        //手机号不能为空
        if (verifyTF.text != nil && verifyTF.text != "" ) {
            Alamofire.request(.POST, verifyCodeURL, parameters: ["code":verifyTF.text!], encoding: .URL, headers: nil).responseJSON { (_, _, result) -> Void in
                //先判断返回的值是否为空，不为空就执行这一步
                if let  value = result.value {
                    //再判断返回的值是success还是fail
                    let state = value["result"] as! String
                    if state == "success" {
                        let resetCipherController = self.storyboard?.instantiateViewControllerWithIdentifier("resetCipherController") as! ResetCipherController
                        self.navigationController?.pushViewController(resetCipherController, animated: true)
                        print(result.value)
                    } else { //如果返回fail
                        self.alertView()
                    }
                }
                    
                else { //如果返回nil
                    self.alertView()
                }
            }
        } else {
            self.disableButton()
            let alert = UIAlertController(title: "提示", message: "验证码不能为空", preferredStyle: UIAlertControllerStyle.Alert)
            let action = UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)
            alert.addAction(action)
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
}

//text field 的
extension ForgetCipherController : UITextFieldDelegate {
    //弹起键盘的
    func dismissKeyboard() {
        //这一句就是收键盘的
        verifyTF.resignFirstResponder()
        phoneNumTF.resignFirstResponder()
    }
    func textFieldDidEndEditing(textField: UITextField) {
        //编辑完了按空白处收键盘
        textField.text = textField.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
        dismissKeyboard()
        if (verifyTF.text != nil && verifyTF.text != "") {
            self.enableButton()
        } else {
            self.disableButton()
        }
    }
    //点击空白处收键盘
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        dismissKeyboard()
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.text = textField.text!.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: " "))
        dismissKeyboard()
        if (verifyTF.text != nil && verifyTF.text != "") {
            self.enableButton()
        } else {
            self.disableButton()
        }
        return true
    }
}
